// 路由配置文件
import Vue from 'vue'
import VueRouter from 'vue-router'
const BaseView = () => import('@/views/BaseView')

const ColumPage = () => import('@/views/ColumPage')

const firstPage = () => import('@/views/firstPage')

const NotFound = () => import('@/views/NotFound')

const SearchResultPage = () => import('@/views/SearchResultPage')

const MasterSupervisor = () => import('@/components/MasterSupervisor')

const TeacherLogin = () => import('@/components/TeacherLogin')

const TeacherProfile = () => import('@/components/TeacherProfile')

const ArticleDetails = () => import('@/components/ArticleDetails')

const ArticleList = () => import('@/components/ArticleList')

const ArticleContent = () => import('@/components/ArticleContent')

const TeacherInfomationForm = () => import('@/components/TeacherInfomationForm')

import service from '@/utils/service'


Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

console.log('欢迎来到动态路由生成文件!');

//原始父栏目
let originalParentColumns = []
//原始子栏目
let originalSubColumns = []
//父栏目路由信息
let parentColumns = [];
//子栏目路由信息
let subColumns = [];


// 创建两个 Promise，分别用于获取原始父栏目和原始子栏目
const getParentColumnsPromise = service.get("/columns/get");
const getSubColumnsPromise = service.get("/columns/getsub");

Promise.all([getParentColumnsPromise, getSubColumnsPromise])
  .then(responses => {
    // 解构 responses 数组以获取响应数据
    const [parentColumnsResponse, subColumnsResponse] = responses;

    // 在这里处理父栏目信息的响应数据
    originalParentColumns = parentColumnsResponse.data.data;
    console.log("从服务器获取到的父栏目为", originalParentColumns);
    //去掉父栏目中的"/""
    parentColumns = originalParentColumns.map(parent => {
      parent.path = parent.path.slice(1);
      return parent;
    });
    console.log("父栏目路由信息", parentColumns);

    // 在这里处理子栏目信息的响应数据
    originalSubColumns = subColumnsResponse.data.data;
    console.log("从服务器获取到的子栏目为", originalSubColumns);
    //去掉子栏目信息前面的父栏目路径
    subColumns = originalSubColumns.map(subcolumn => {
      var parts = subcolumn.path.split("/");
      subcolumn.path = parts[2];

      return subcolumn;

    });
    console.log("子栏目路由信息", subColumns);

    //动态生成路由
    const dynamicroutes = parentColumns.map(parent => {
      //对于每一个parent

      //计算当前父栏目对应的子栏目
      const relatedSubColumns = subColumns.filter(sub => sub.column_id === parent.column_id);

      //动态生成父路由
      const parentRoute = {
        path: parent.path,
        component: ColumPage,
        //调用重定向函数
        redirect: determineredirect(parent, relatedSubColumns),
        children: []
      };

      //对当前父栏目生成其子路由
      relatedSubColumns.forEach(sub => {
        let subRoute = {
          path: sub.path,
          //决定子路由调用哪个组件
          component: determineComponent(sub)

        };

        parentRoute.children.push(subRoute);
        //如果子栏目是文章列表，则为其添加文章详情页组件
        if (sub.type === 0) {
          parentRoute.children.push({
            path: `${sub.path}/details/:articleId`,
            component: ArticleDetails,
            props: true
          });
        }
        ;


      });

      //判断当前子栏目是否是师资队伍
      if (parent.column_id === 3) {
        //添加登录组件
        parentRoute.children.push({
          path: 'qdrkdz',
          component: TeacherLogin
        },);
        //添加教师表单组件
        parentRoute.children.push({
          path: 'InfoForm',
          component: TeacherInfomationForm,
        });
        //添加教师个人资料展示组件
        parentRoute.children.push({
          path: 'Profile',
          component: TeacherProfile,
          props: (route) => ({
            id: route.query.id
          })

        });
      }
      return parentRoute;
    });

    //合并路由函数
    const mergedroutes = (dynamicroutes) => {

      const otherroutes = [
        {
          path: 'search',
          component: SearchResultPage,

        },
        {
          path: parentColumns[0].path+'/homepage',
          component: firstPage,

        },
      ]

      const allRoutes = [...otherroutes, ...dynamicroutes];
      return allRoutes;

    }
    //动态添加的路由
    const newRoute = {
      path: '/',
      component: BaseView,
      redirect:'/'+parentColumns[0].path+'/homepage',
      //生成路由
      children: mergedroutes(dynamicroutes)
    }

    router.addRoute(newRoute);

    //动态添加未找到页面路由
    const notfoundRoute = {
      path: '*',
      component: NotFound,
    }

    router.addRoute(notfoundRoute);


    console.log(router.getRoutes());


  })
  .catch(errors => {
    // 处理错误
    console.error('Errors:', errors);
  });


//决定重定向函数
const determineredirect = (parent, relatedSubColumns) => {
  if (parent.column_id === 1) {
    return '/'+parent.path+'/'+'homepage';
  } else if (relatedSubColumns.length > 0) {
    return '/' + parent.path + '/' + relatedSubColumns[0].path;
  }

}


//根据子栏目类型决定加载哪个组件
const determineComponent = (subcolumn) => {
  if (subcolumn.type === 2) {
    return MasterSupervisor;
  } else if (subcolumn.type === 0) {
    return ArticleList;
  } else if (subcolumn.type === 1) {
    return ArticleContent;
  } else {
    return null;
  }
};


//基本路由
const routes = [

];


const router = new VueRouter({
  mode: 'history',
  routes
})


export default router
